import 'dart:convert';

import 'package:animated_digit/animated_digit.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_svg/svg.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:spree/pages/games/game_manual.dart';
import 'package:spree/pages/games/games_auto.dart';
import 'package:spree/pages/games/games_table.dart';
import 'package:spree/utils/utils.dart';
import 'package:spree/widgets/common_container.dart';
import 'package:spree/widgets/vip_content_box.dart';
import 'package:spree/widgets/vip_rectangle_box.dart';
import 'package:socket_io_client/socket_io_client.dart' as IO;
import '../../../../provider/model/user_model.dart';
import '../../../../utils/account.dart';
import '../../../../utils/api.dart';
import '../../../../utils/videoUtil.dart';
import '../../game_progress.dart';
import '../../game_title_bar.dart';

class DoublePage extends StatefulWidget {
  DoublePage({Key? key}) : super(key: key);

  @override
  State<DoublePage> createState() => _DoublePageState();
}

class _DoublePageState extends State<DoublePage> with TickerProviderStateMixin {
  late TabController _tabController;
  late TabController _tabController2;
  late AnimatedDigitController _accountAmountController;

  List _tabs = ["Manual", "Auto"];
  List _tabs2 = ["My Bets", "History", "Player List"];
  int _fIndex = 0;
  int _fIndex2 = 0;
  double progress = 10;
  String progressStr = "";
  int currentNumber = 0;
  final IO.Socket _socket = IO.io(
      'http://47.95.0.143:9005',
      IO.OptionBuilder()
          .setPath('/game/socket.io')
          .setTransports(['websocket'])
          .disableAutoConnect()
          .build());
  int select = -3;
  bool hasClickBet = false;
  late ScrollController _controller;
  late AnimationController progressAnimationController =
      AnimationController(vsync: this, duration: Duration(milliseconds: 10000));
  late Animation progressAnimation =
      Tween(begin: 0.0, end: 1.0).animate(progressAnimationController);
  List<String> _list = [
    '0',
    '1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    '10',
    '11',
    '12',
    '13',
    '14'
  ];
  List<Map> _tableData = [
    {
      'time': '10/12/22 14:24:20',
      'RoundID': '18:22',
      'Result': '1',
      'Basebet': '10',
      'Profit': '-10'
    }
  ];
  List _tableHeader = ['time', 'RoundID', 'Result', 'Basebet', 'Profit'];
  //显示相关的
  bool progressVisible = true;
  bool progressTextVisible = true;
  bool placeBetVisible = true;

  //默认选中的颜色
  String color = "RED";
  double inputMoney = 0.0;
  List rollHistoryNumber = [];
  bool hasPlayedVideo = false;

  double _money = 0;
  // 表头
  List<String> _myBetHeader = [
    'Time',
    'Round ID',
    'Result',
    'Basebet',
    'Profit'
  ];
  List<String> _playerHeader = ['Player', 'Cash Out', 'Bets'];
  List<String> _historyHeader = ['Round ID', 'Time', 'Result'];
  // 数据
  List<Map> _myBetData = [
    // {
    //   'time': '10/12/22 14:24:20',
    //   'roundID': '4213212121',
    //   'result': '1',
    //   'baseBet': '23.00',
    //   'profit': '312321'
    // }
  ];
  List<Map> _playerData = [
    // {'player': 'User2122322222222', 'cashOut': '1.2x', 'bets': '50'}
  ];

  List<Map> _history = [
    // {'roundID': '112324001', 'time': '2023-01-02', 'result': '1'}
  ];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _tabController = TabController(length: _tabs.length, vsync: this);
    _tabController2 = TabController(length: _tabs2.length, vsync: this);
    wsConnect(context);

    getMyBetsAndAccount();
    setState(() {});
    progressAnimation.addListener(() {
      setState(() {
        progress = (1 - progressAnimation.value) * 10;
        progressStr = progress.toStringAsFixed(2);
        if (progress <= 5 && !hasPlayedVideo) {
          VideoUtil.playVideoByUrl("sounds/time_delay.mp3");
          hasPlayedVideo = true;
        }
      });
    });
    progressAnimation.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        placeBetVisible = false;
        progressVisible = false;
        progressTextVisible = false;
        hasPlayedVideo = false;
      }
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    progressAnimationController.dispose();
    _tabController.dispose();
    _tabController2.dispose();
    if (_socket != null) {
      _socket.clearListeners();
      _socket.disconnect();
    }
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
    _controller = ScrollController(initialScrollOffset: offsetInit());
  }

// 初始化ws
  wsConnect(BuildContext context) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      String? accessToken = context.read<UserModel>().accessToken;
      String? userId = context.read<UserModel>().userId;
      _socket.connect();
      _socket.onConnect((data) async {
        Map pre = {'gameType': 'DOUBLE'};
        sendMsg('game_enter', pre);

        _onMessage(userId);
      });
      _socket.onDisconnect((data) {
        print('断开=====');
      });

      // _onMessage(context);
    } catch (e) {
      print(e);
    }
  }

  // 监听消息
  _onMessage(String? userId) {
    try {
      _socket.on('game_start_time', ((data) {
        if (mounted) {
          progressRun(data);
        }
      }));
      _socket.on('game_enter', (data) {
        if (mounted) {
          progressRun(data);
        }
      });
      _socket.on('game_start', (data) async {
        Map result = jsonDecode(data);
        bool win = result['win'];
        double amount = inputMoney;
        if (win) {
          _accountAmountController.addValue(result['winAmount']);
          amount = double.parse(result['winAmount'].toString());
        } else {
          _accountAmountController.addValue(-amount);
        }
        Future.delayed(Duration(milliseconds: 2000), (() {
          showResult(win, amount);
        }));
        getMyBets();
      });
      //下单是否成功
      _socket.on('game_bet', ((data) {
        hasClickBet = true;
        Map result = jsonDecode(data);
        bool success = result['success'];
        if (success) {
          EasyLoading.showSuccess("your bet is placed");
        }
        if (!success) {
          setState(() {
            hasClickBet = false;
          });
          String errorMsg = result['errorMsg'];
          _showChargeAlert(errorMsg);
        }
      }));
      _socket.on("double_result", ((data) {
        Map result = jsonDecode(data);
        int rollNumber = int.parse(result['rollNumber']);
        setState(() {
          currentNumber = rollNumber;
        });
        _startAnimate();
      }));
      _socket.on("game_history", ((data) {
        List result = jsonDecode(data);
        rollHistoryNumber = [];
        for (int i = 0; i < result.length; i++) {
          rollHistoryNumber.add(result[i]['mutiplier']);
        }
        _history = [];
        // 游戏下方的记录
        // {'roundID': '112324001', 'time': '2023-01-02', 'result': '1.2x'}
        if (result.length > 0) {
          for (int i = 0; i < result.length; i++) {
            _history.add({
              'roundID': result[i]['roundId'],
              'time': result[i]['time'],
              'result': result[i]['mutiplier']
            });
          }
        }
      }));
      _socket.on("game_real_time_double", ((data) {
        // {'player': 'User2122322222222', 'cashOut': '1.2x', 'bets': '50'}
        List result = jsonDecode(data);
        _playerData = [];
        if (result.length > 0) {
          for (int i = 0; i < result.length; i++) {
            _playerData.add({
              'player': result[i]['userName'],
              'cashOut': result[i]['mutiplier'].toString() + 'x',
              'bets': result[i]['betAmount'],
              'win': result[i]['win']
            });
          }
        }
      }));
    } catch (e) {
      print(e);
    }
  }

  // 发送消息
  sendMsg(msg, prama) {
    print(prama);
    try {
      _socket.emit(msg, prama);
    } catch (e) {}
  }

  // 断开连接
  disConnect() {
    try {
      _socket.onDisconnect((data) {});
    } catch (e) {}
  }

  progressRun(data) {
    Map result = jsonDecode(data);
    setState(() {
      progressVisible = true;
      progressTextVisible = true;
      placeBetVisible = true;
    });
    int startTime = result['gameStartTime'];
    int current = result['current'];
    int delay = startTime - current - 500;
    if (delay < 0) {
      delay = 100;
    }
    if (delay <= 4000) {
      hasPlayedVideo = true;
    }
    progressAnimationController.reset();
    progressAnimationController.duration = Duration(milliseconds: delay);
    progressAnimationController.forward();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            SvgPicture.asset('images/BETSPREELOGO.svg'),
            Consumer<UserModel>(builder: (context, value, child) {
              return _circleMoney();
            })
          ],
        ),
      ),
      body: Consumer<UserModel>(builder: (context, value, child) {
        return CommonContainer(
          child: ListView(
            children: [
              GameTitleBar(
                gameName: 'Double',
                ontap: (type) {
                  if (type == 'info') {
                    Navigator.pushNamed(context, 'DoubleRules');
                  }
                },
              ),
              Container(
                padding: EdgeInsets.all(10),
                decoration: BoxDecoration(
                  color: Utils().createMaterialColor(),
                  borderRadius: BorderRadius.all(Radius.circular(10.0)),
                  boxShadow: [
                    BoxShadow(
                        color: Color(0xFF261E54),
                        offset: Offset(0.0, 1.0),
                        blurRadius: 1,
                        spreadRadius: 2)
                  ],
                ),
                child: Column(
                  children: [
                    rolls(),
                    Visibility(
                      visible: progressVisible,
                      maintainAnimation: true,
                      maintainSize: true,
                      maintainState: true,
                      child: ConstrainedBox(
                        constraints: BoxConstraints(maxWidth: 200),
                        child: SliderTheme(
                          data: SliderTheme.of(context)
                              .copyWith(thumbShape: ProgressBar()),
                          child: Slider(
                            value: progress,
                            max: 10,
                            min: 0,
                            activeColor: Color(0xFF5484FF),
                            inactiveColor: Color(0xFFFF3F61),
                            onChanged: (value) {},
                          ),
                        ),
                      ),
                    ),
                    Visibility(
                      visible: progressTextVisible,
                      maintainAnimation: true,
                      maintainSize: true,
                      maintainState: true,
                      child: Text(
                        '$progressStr',
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 12,
                            fontWeight: FontWeight.w800),
                      ),
                    ),
                    Visibility(
                      visible: placeBetVisible,
                      maintainAnimation: true,
                      maintainSize: true,
                      maintainState: true,
                      child: Padding(
                        padding: EdgeInsets.only(top: 20),
                        child: Text(
                          'Place your Bet',
                          style: TextStyle(color: Colors.white, fontSize: 14),
                        ),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(top: 20),
                      child: Container(
                        height: 60,
                        child: _listView(
                            Utils().getScreenWidth(context) - 50 - 15),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(top: 20),
                      child: Image.asset(
                        'images/up-arrow.png',
                        height: 40,
                      ),
                    )
                  ],
                ),
              ),
              TabBar(
                controller: _tabController,
                tabs: _tabs.map((e) => Tab(text: e)).toList(),
                onTap: (i) {
                  setState(() {
                    _fIndex = i;
                  });
                },
              ),
              _fIndex == 1
                  ? Container()
                  : GameManual(
                      disabled: hasClickBet,
                      onColorClick: (data) {
                        color = data['color'];
                      },
                      onBETClick: (data) {
                        // _showDialog(true, title: '2.4x', subTitle: 'Sorry you lose');
                        if (data['inputMoney'] == '') {
                          EasyLoading.showToast('please typed in amount');
                          return;
                        }
                        if (progressAnimation.isCompleted) {
                          EasyLoading.showToast('please wait next round');
                          return;
                        }
                        // _showChargeAlert();
                        // return;
                        inputMoney = double.parse(data['inputMoney']);
                        order();
                      },
                    ),
              TabBar(
                indicator: const UnderlineTabIndicator(
                    borderSide: BorderSide(width: 2.0, color: Colors.red)),
                controller: _tabController2,
                tabs: _tabs2.map((e) => Tab(text: e)).toList(),
                onTap: (i) {
                  setState(() {
                    _fIndex2 = i;
                  });
                },
              ),
              VipRectangleBox(
                color: Color(0xFF291F62),
                child: SingleChildScrollView(
                  scrollDirection: Axis.horizontal,
                  child: _tableList(_fIndex2),
                ),
              ),
            ],
          ),
        );
      }),
    );
  }

  Widget _numberRectangleBox({
    double? width = 60,
    double? height = 60,
    String? number = '5',
    EdgeInsets? margin,
    Color? color,
    Color? circularColor,
  }) {
    return Container(
      margin: margin ?? EdgeInsets.only(left: 3),
      padding: EdgeInsets.all(4),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(10.0)), color: color),
      child: Container(
        width: width,
        height: height,
        alignment: Alignment.center,
        decoration: BoxDecoration(
            shape: BoxShape.circle,
            border: Border.all(width: 1, color: circularColor ?? Colors.white)),
        child: Text(
          number ?? '',
          style: TextStyle(color: circularColor ?? Colors.white, fontSize: 20),
        ),
      ),
    );
  }

  _showChargeAlert(msg) {
    showDialog(
        barrierDismissible: false,
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("Tips"),
            content: Text("$msg"),
            actions: <Widget>[
              TextButton(
                child: Text("Cancel"),
                onPressed: () => Navigator.of(context).pop(),
              ),
              TextButton(
                child: Text("Deposit"),
                onPressed: () {
                  // 跳转到充值页面
                  Navigator.of(context).pop(true); //关闭对话框
                },
              ),
            ],
          );
        });
  }

  //开始动画并且展示输赢
  _startAnimate() {
    double width = Utils().getScreenWidth(context) - 65;
    double singleWidth = width / 7;
    int moveStep = 0;
    if (currentNumber - 3 < 0) {
      moveStep = currentNumber + 12;
    } else {
      moveStep = currentNumber - 3;
    }
    _controller.animateTo(singleWidth * moveStep,
        duration: const Duration(milliseconds: 1000),
        curve: Curves.easeOutQuint);
    hasClickBet = false;
  }

  //展示输赢的结果
  showResult(win, amount) {
    if (win) {
      VideoUtil.playVideoByUrl("sounds/mines/mines-win.mp3");
      _showDialog(false, title: amount.toString(), subTitle: "Winning");
    } else {
      VideoUtil.playVideoByUrl("sounds/mines/mines-lose.mp3");
      _showDialog(true, title: amount.toString(), subTitle: "Sorry you Lose");
    }
  }

  Widget _listView(double width) {
    double singleItemWidth = width / 7;
    return Stack(
      children: <Widget>[
        NotificationListener<ScrollNotification>(
          child: ListView.builder(
            controller: _controller,
            itemCount: _list.length * 10000,
            itemExtent: width / 7,
            physics: new NeverScrollableScrollPhysics(),
            itemBuilder: (BuildContext context, int index) {
              return _listViewItem(
                  _list[index % _list.length], index, singleItemWidth);
            },
            scrollDirection: Axis.horizontal,
          ),
          onNotification: (notification) {
            if (notification is ScrollEndNotification) {
              Future.delayed(Duration(milliseconds: 2000), (() {
                if (mounted) {
                  _controller.jumpTo(offsetInit());
                }
              }));
            }
            return true;
          },
        ),
      ],
    );
  }

  Widget _listViewItem(String title, int index, double singleItemWidth) {
    int num = int.parse(title);
    Color colorNum = Colors.white;
    if (num.isOdd) {
      colorNum = Color(0xFFFF506F);
    }
    if (num.isEven && num != 0) {
      colorNum = Color(0xFF3D77E8);
    }
    if (num == 0) {
      colorNum = Colors.white;
    }
    return GestureDetector(
      onTap: () {
        // 滚动到中间位置
        double offset = (index - 3) * singleItemWidth;
        _controller.jumpTo(offset);
      },
      child: Container(
        alignment: Alignment.center,
        child: _numberRectangleBox(
            color: colorNum,
            circularColor: num == 0 ? Colors.black : Colors.white,
            number: title,
            height: 42),
      ),
    );
  }

  offsetInit() {
    if (mounted) {
      double screenWidth = MediaQuery.of(context).size.width;
      double fixOffset = screenWidth - 65;
      return (3000 + select) * (fixOffset) / 7;
    }
  }

  order() async {
    final prefs = await SharedPreferences.getInstance();
    String? userId = context.read<UserModel>().userId;

    Map param = {
      'amount': inputMoney,
      'color': color,
      'isfast': false,
      'gameType': 'DOUBLE',
      'userId': userId
    };
    sendMsg("game_bet", param);
  }

  Widget rollNumber(num) {
    Color colorNum = Colors.white;
    if (num != null) {
      if (num.isOdd) {
        colorNum = Color(0xFFFF506F);
      }
      if (num.isEven && num != 0) {
        colorNum = Color(0xFF3D77E8);
      }
      if (num == 0) {
        colorNum = Colors.white;
      }
    }
    return _numberRectangleBox(
        color: colorNum,
        circularColor: num == 0 ? Colors.black : Colors.white,
        number: num.toString(),
        height: 30,
        width: 30);
  }

  Widget rolls() {
    List<Widget> rollsWidget = [];

    int size = rollHistoryNumber.length;
    // for (int i = 7; i >= 0; i--) {
    //   rollsWidget.add(rollNumber(5));
    // }
    if (size > 0) {
      if (size >= 6) {
        for (int i = 5; i >= 0; i--) {
          rollsWidget.add(rollNumber(rollHistoryNumber[i]));
        }
      } else {
        for (int i = size - 1; i >= 0; i--) {
          rollsWidget.add(rollNumber(rollHistoryNumber[i]));
        }
      }
    }
    return Row(
      children: [
        Padding(
          padding: EdgeInsets.only(left: 10, right: 10),
          child: Text(
            'Previous Rolls',
            style: TextStyle(color: Utils().whiteColor()),
          ),
        ),
        Expanded(
          child: SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: Row(
              children: rollsWidget,
            ),
          ),
          flex: 1,
        )
      ],
    );
  }

  // 边框的container
  Border _loutLine() {
    return Border.all(width: 1, color: Color.fromRGBO(255, 255, 255, 0.5));
  }

  Widget _tableList(index) {
    if (index == 1) {
      return DataTable(
        columns: _historyHeader.map((e) {
          return DataColumn(
            label: Text(
              '$e',
              style: TextStyle(color: Colors.white38),
            ),
          );
        }).toList(),
        rows: _createTableRow(_history, ['roundID', 'time', 'result']),
      );
    }
    if (index == 2) {
      return DataTable(
        columns: _playerHeader.map((e) {
          return DataColumn(
            label: Text(
              '$e',
              style: TextStyle(color: Colors.white38),
            ),
          );
        }).toList(),
        rows: _createTableRow(_playerData, ['player', 'cashOut', 'bets']),
      );
    }
    return DataTable(
      columns: _myBetHeader.map((e) {
        return DataColumn(
          label: Text(
            '$e',
            style: TextStyle(color: Colors.white38),
          ),
        );
      }).toList(),
      rows: _createTableRow(
          _myBetData, ['time', 'roundID', 'result', 'baseBet', 'profit']),
    );
  }

  List<DataRow> _createTableRow(List<Map> data, List<String> keys) {
    return data.map((e) => DataRow(cells: _createTableCell(e, keys))).toList();
  }

  List<DataCell> _createTableCell(Map data, List<String> keys) {
    return keys.map((e) {
      if (e == 'result' && _fIndex2 == 0) {
        Color colorNum = Color(0xFFFF506F);
        return DataCell(Row(
          children: [
            _numberRectangleBox(
                color: colorNum,
                circularColor: Colors.white,
                number: '${data[e]}',
                width: 32,
                height: 32),
            Padding(
              padding: EdgeInsets.only(left: 4, right: 4),
              child: Text(
                '/',
                style: TextStyle(color: Colors.white, fontSize: 32),
              ),
            ),
            _numberRectangleBox(
                color: colorNum,
                circularColor: Colors.white,
                number: '${data[e]}',
                width: 32,
                height: 32)
          ],
        ));
      }
      if (e == 'result' && _fIndex2 == 1) {
        int result = data['result'];
        Color colorNum = Colors.white;
        if (result.isOdd) {
          colorNum = Color(0xFFFF506F);
        }
        if (result.isEven && num != 0) {
          colorNum = Color(0xFF3D77E8);
        }
        if (result == 0) {
          colorNum = Colors.white;
        }
        return DataCell(Row(
          children: [
            _numberRectangleBox(
                color: colorNum,
                circularColor: result == 0 ? Colors.black : Colors.white,
                number: '${data[e]}',
                width: 32,
                height: 32),
          ],
        ));
      }
      if (e == 'cashOut') {
        return DataCell(
          Container(
            width: 50,
            height: 20,
            decoration: const BoxDecoration(
              color: Colors.red,
              borderRadius: BorderRadius.all(Radius.circular(3.0)),
            ),
            alignment: Alignment.center,
            child: Text(
              '${data[e]}',
              style: TextStyle(color: Colors.white),
            ),
          ),
        );
      }
      if (e == 'baseBet') {
        return DataCell(Row(
          children: [
            Text(
              'R\$ ',
              style: TextStyle(color: Color(0xFFFFED4A)),
            ),
            Text(
              '${data[e]}',
              style: TextStyle(color: Colors.white60),
            )
          ],
        ));
      }
      if (e == 'profit') {
        Color color = Colors.red;
        double result = data['profit'];
        if (result > 0) {
          color = Colors.green;
        }
        return DataCell(Row(
          children: [
            Text(
              'R\$ ',
              style: TextStyle(color: Color(0xFFFFED4A)),
            ),
            Text(
              '${data[e]}',
              style: TextStyle(color: color),
            )
          ],
        ));
      }
      return DataCell(Text(
        '${data[e]}',
        style: TextStyle(color: Colors.white60),
      ));
    }).toList();
  }

  getMyBets() async {
    //当前时间倒推1个月
    var now = DateTime.now();
    DateTime newMonth = DateTime(now.year, now.month - 1, now.day);
    String endDate = DateFormat("yyyy-MM-dd").format(now);
    String startDate = DateFormat("yyyy-MM-dd").format(newMonth);

    Map param = {
      'gameType': 'DOUBLE',
      'startDate': startDate,
      'endDate': endDate,
      'limit': 20,
      'pageSize': 10
    };
    try {
      dynamic result = await Api.historyInfo(param);
      List tempData = result['data'];
      _myBetData = [];
      if (tempData.length > 0) {
        for (int i = 0; i < tempData.length; i++) {
          _myBetData.add({
            'time': tempData[i]['playTime'],
            'roundID': tempData[i]['recordNo'],
            'result': '1',
            'baseBet': tempData[i]['betAmount'],
            'profit': tempData[i]['winAmount']
          });
        }
      }
    } catch (e) {}
  }

  // 显示弹出层
  _showDialog(bool isLose, {String? title, String? subTitle}) {
    showDialog(
        barrierDismissible: false,
        context: context,
        builder: (BuildContext context) {
          return Stack(
            children: [
              Positioned(
                left: (Utils().getScreenWidth(context) - 100) / 2,
                top: 300,
                child: Container(
                  width: 100,
                  height: 35,
                  alignment: Alignment.center,
                  child: Text(
                    title ?? '',
                    style: TextStyle(
                        color: Colors.white, fontWeight: FontWeight.w700),
                  ),
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: isLose
                          ? AssetImage('images/games/double/red-top.png')
                          : AssetImage('images/games/double/yellow-top.png'),
                      fit: BoxFit.fill, // 完全填充
                    ),
                  ),
                ),
              ),
              Positioned(
                top: 330,
                left: (Utils().getScreenWidth(context) - 200) / 2,
                child: Container(
                  width: 200,
                  height: 50,
                  alignment: Alignment.center,
                  child: Text(
                    subTitle ?? '',
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 20,
                        fontWeight: FontWeight.w700),
                  ),
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: isLose
                          ? AssetImage('images/games/double/red-bottom.png')
                          : AssetImage('images/games/double/blue-bottom.png'),
                      fit: BoxFit.fill, // 完全填充
                    ),
                  ),
                ),
              )
            ],
          );
        });
    Future.delayed(Duration(seconds: 1), () {
      Navigator.of(context).pop();
    });
  }

  getMyBetsAndAccount() {
    String? userId = context.read<UserModel>().userId;
    if (userId != '') {
      Account.refreshAccount(context);
      Future.delayed(Duration(milliseconds: 1), (() {
        getMyBets();
      }));
      setState(() {});
    }
    String accountAmount = context.read<UserModel>().accountAmount;
    if (accountAmount != '') {
      _accountAmountController =
          AnimatedDigitController(double.parse(accountAmount));
    } else {
      _accountAmountController = AnimatedDigitController(0.00);
    }
  }

  _circleMoney({double? width, String? money}) {
    return Row(
      children: [
        Container(
          width: width,
          margin: EdgeInsets.only(left: 12),
          padding: EdgeInsets.only(top: 4, bottom: 4, left: 8, right: 8),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(20.0)),
              border: Border.all(color: Color(0xFF9C4EFF), width: 1)),
          child: Row(
            children: [
              Container(
                width: 24,
                height: 24,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: Color(0xFF9174FB),
                    borderRadius: BorderRadius.all(Radius.circular(12.0))),
                child: Text(
                  "R\$",
                  style: TextStyle(
                    fontSize: 10,
                    color: Colors.white,
                  ),
                ),
              ),
              Padding(
                padding: EdgeInsets.only(left: 5),
                child: AnimatedDigitWidget(
                  value: _accountAmountController.value,
                  textStyle: TextStyle(color: Colors.white, fontSize: 10),
                  fractionDigits: 2,
                  enableDigitSplit: true,
                  digitSplitSymbol: ",",
                ),
              )
            ],
          ),
        ),
        Padding(
          padding: EdgeInsets.only(left: 20),
          child: GestureDetector(
            onTap: () {
              Navigator.pushNamed(context, 'WithdrawnPage');
            },
            child: Image.asset(
              'images/wallet-app-bar.png',
              width: 24,
            ),
          ),
        )
      ],
    );
  }
}
